package org.broadway.monitor;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.broadway.exceptions.CollectorException;
import org.broadway.interfaces.ResourceCollector;

/**
 * This class implements a mapped resource collector.  Resources are stored in a map container.
 * The number of collected items is always equals to the number of items in the collector.
 * 
 * @author vmatters
 *
 */
public class MappedResourceCollector implements ResourceCollector<Map<String,Object>> {
	private static Log log = LogFactory.getLog(MappedResourceCollector.class);
	private Map<String,Object> resources;
	/**
	 * Constructor
	 *
	 */
	public MappedResourceCollector() {
		super();
		resources = new HashMap<String,Object>();
	}
	
	/**
	 * Constructor which accepts an existing resources.
	 * @param resources
	 */
	public MappedResourceCollector(Map<String,Object> resources){
		super();
		this.resources = resources;
	}
	
	/**
	 * Call this method to add a resource to the collector.
	 * @param key - key used to identify the added resource in the map.
	 * @param value - actual value for the added resource.
	 */
	public void putResource(String key, Object value){
		this.getResources().put(key, value);
		log.debug("Resource with key " + key + " added to resource collector.");
	}
	
	/**
	 * Returns a resource from the collector.
	 * @param key - key for queried resource.
	 * @return instance of resource object.
	 */
	public Object getResource(String key) {
		return this.getResources().get(key);
	}
	
	/**
	 * Removes a resource from the collector.
	 * @param key - key for resource to remove.
	 */
	public void removeResource(String key) {
		this.getResources().remove(key);
		log.debug("Removed resource with key " + key + " from resource collector.");
	}
	
	/**
	 * This is the implemented method for the collector. When called,
	 * this method returns the resources stored in by the item collector.
	 */
	public Map<String,Object> collect() throws CollectorException {
		return  this.getResources();
	}
	
	/**
	 * Returns resources stored in the collector (equivalent to calling collect() in this case).
	 * @return
	 */
	public Map<String,Object> getResources() {
		if(resources == null){
			resources = new HashMap<String,Object>();
		}
		return resources;
	}
	
	/**
	 * Sets an existing map as data source for resources.
	 * @param resources
	 */
	public void setResources(Map<String,Object> resources) {
		this.resources = resources;
	}

}
